package com.ha7419x.controller;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.Charset;

@Controller
public class ConsumerUploadController {

    public static final String UPLOAD_URL = "http://zdmin:123456@gateway-9501.com:9501/demo/upload-proxy/upload";

    @RequestMapping(value = "/consumer/uploadPre", method = RequestMethod.GET)
    private String uploadPre() {
        return "upload";
    }

    @RequestMapping(value = "/consumer/upload", method = RequestMethod.POST)
    private @ResponseBody String upload(String name, MultipartFile photo) throws IOException {
        if(photo != null) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CredentialsProvider provider = new BasicCredentialsProvider();//认证访问信息
            Credentials credentials = new UsernamePasswordCredentials("zdmin","123456");
            provider.setCredentials(AuthScope.ANY, credentials);    //认证请求都使用一个认证信息
            HttpClientContext httpContext = HttpClientContext.create();//处理操作的上下文对象
            httpContext.setCredentialsProvider(provider);
            HttpPost httpPost = new HttpPost(UPLOAD_URL);//设置请求地址
            HttpEntity httpEntity = MultipartEntityBuilder.create()
                    .addBinaryBody("photo", photo.getBytes(), ContentType.create("image/jpeg"), "temp.jpg").build();
            httpPost.setEntity(httpEntity);
            HttpResponse httpResponse = httpClient.execute(httpPost, httpContext);
            return EntityUtils.toString(httpResponse.getEntity(), Charset.forName("UTF-8"));
            /*return "【*** 消费端 ***】name = " + name + "、photoName = " + photo.getOriginalFilename() + "、ContentType = " + photo.getContentType();*/
        } else {
            return "noPhoto.jpg";
        }
    }
}
